package com.atguigu.lease.web.admin.interceptors;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.jwts.JwtUtil;
import com.atguigu.lease.common.redis.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.el.parser.Token;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author zhaolingqiao
 * @CreateTime 2024/12/14
 * description:设置拦截器，每次请求校验token
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 每次请求，都会校验token
     * 不是登录，需携带token，
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String accessToken = request.getHeader("access_token");
        //token是否为null
        if(ObjectUtils.isEmpty(accessToken)){
            //是null,未登录
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        //校验token是否过期和有效,
        // 如果有错误，内部抛异常
        JwtUtil.parseToken(accessToken);
        //放行，执行方法
        return true;
    }
}
